package org.douxiaoban.client.api;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.douxiaoban.client.app.App;
import org.douxiaoban.client.app.Assistant;

import android.util.Log;

/**
 * Created by IntelliJ IDEA.
 * User: huangzhongkun
 * Date: 11-6-14
 * Time: 下午8:03
 */
public class TopSubjectParser {
    private static Pattern _book_regular = Pattern.compile("\\\"detail\\-frame\\\"\\s*\\>.*?<\\s*\\/li\\s*>",Pattern.CASE_INSENSITIVE);
    private static Pattern _book_title_regular = Pattern.compile("<\\s*h\\d+\\s*>.*?<\\s*/h\\d+\\s*>",Pattern.CASE_INSENSITIVE);
    private static Pattern _book_attribute_regular = Pattern.compile("color-gray\">.*?<\\s*/p\\s*>",Pattern.CASE_INSENSITIVE);
    private static Pattern _book_content_regular = Pattern.compile("<\\s*p\\s*>.*?<\\s*/p\\s*>",Pattern.CASE_INSENSITIVE);
    private static Pattern _book_id_regular = Pattern.compile("href=\"http.*?\"");
    private static Pattern _book_imag_regular = Pattern.compile("src=\"http\\:.*\"",Pattern.CASE_INSENSITIVE);

    private static Pattern _movie_regular = Pattern.compile("\\<li\\s*class=\"clearfix\"\\>.*?\\<\\/li\\>",Pattern.CASE_INSENSITIVE);
    private static Pattern _movie_id_regular = Pattern.compile("<a.*?>",Pattern.CASE_INSENSITIVE);
    private static Pattern _movie_img_regular = Pattern.compile("<\\s*img\\s*src=\"http.*?\"",Pattern.CASE_INSENSITIVE);
    private static Pattern _movie_content_regular = Pattern.compile("<\\s*span\\sclass=\"pl\">.*?\\<\\/span>",Pattern.CASE_INSENSITIVE);
    private static Pattern _movie_rating_num_regular = Pattern.compile("<span\\s*class=\"allstar.*?div",Pattern.CASE_INSENSITIVE);;
    //private static Pattern _movie_rating_num_regular = Pattern.compile("<\\s*span\\s*class=\"rating_nums\"\\s*>.*?</span\\s*>",Pattern.CASE_INSENSITIVE);
    //private static Pattern _movie_rating_average_regular = Pattern.compile("<\\s*span\\s*class=\"pl\"\\s*>.*?</span\\s*>",Pattern.CASE_INSENSITIVE);
    private static Pattern _movie_title_regular = Pattern.compile("<\\s*h\\d*\\s*>.*?<\\s*/h\\d*\\s*>");

    private static Pattern _music_regular = _movie_regular;
    private static Pattern _music_id_regular = Pattern.compile("<a.*?href=\".*\">",Pattern.CASE_INSENSITIVE);
    private static Pattern _music_img_regular = _movie_img_regular;
    private static Pattern _music_title_reguar = Pattern.compile("<\\s*h\\d*\\s*>.*?<\\s*/h\\d*\\s*>");
    private static Pattern _music_rating_num_regular = Pattern.compile("<span\\s*class=\"allstar.*?div",Pattern.CASE_INSENSITIVE);
    private static Pattern _music_content_regular = Pattern.compile("class=\"pl\">.*?<br\\/>",Pattern.CASE_INSENSITIVE);

    private static String _music_url = "http://music.douban.com";
    private static String _book_url = "http://book.douban.com";
    private static String _movie_url = "http://movie.douban.com";


    public static ArrayList<TopSubjectRecord> getNewMusic(){
           ArrayList<TopSubjectRecord> regularRecordArrayList = new ArrayList<TopSubjectRecord>();
           StringBuffer stringBuffer = new StringBuffer();

               try {
                   URL music_url = new URL(_music_url);
                   URLConnection urlConnection = music_url.openConnection();
                   InputStreamReader inputStreamReader =
                           new InputStreamReader(urlConnection.getInputStream());
                   BufferedReader reader = new BufferedReader(inputStreamReader);
                   String temp;

                   while ((temp = reader.readLine())!=null){
                       stringBuffer.append(temp);
                   }
                   inputStreamReader.close();
                   reader.close();


                   Matcher matcher = _music_regular.matcher(stringBuffer.toString());

                   while (matcher.find()){
                      String pattern_str = matcher.group();
                      TopSubjectRecord topSubjectRecord = new TopSubjectRecord();

                      Matcher matcher2 = _music_id_regular.matcher(pattern_str);
                      if(matcher2.find()){
                          String[] id_arr = matcher2.group().split("\"");
                          topSubjectRecord.id = id_arr[3];
                          topSubjectRecord.image_url = id_arr[5];

                          topSubjectRecord.image_url = topSubjectRecord.image_url.replaceFirst("spic","mpic");
                          if(App.NETWORK_STATUS == Assistant.WIFI)
                              topSubjectRecord.image_url = topSubjectRecord.image_url.replaceFirst("mpic","lpic");

                          //System.out.println("music:"+topSubjectRecord.id+"|"+topSubjectRecord.image_url);
                      }


                      matcher2 = _music_content_regular.matcher(pattern_str);
                      while(matcher2.find()){
                          String[] content_arr = matcher2.group().split(">");
                          String content = content_arr[content_arr.length-1];
                          content = content.substring(0,content.length()-4);
                           if(topSubjectRecord.content==null)
                            topSubjectRecord.content = content;
                          else
                            topSubjectRecord.content += "|"+content;

                          System.out.println("contetn:"+topSubjectRecord.content);
                      }

                      matcher2 = _music_title_reguar.matcher(pattern_str);
                       if(matcher2.find()){

                           String[] title_arr = matcher2.group().split(">");
                           String title = title_arr[title_arr.length-2];
                            topSubjectRecord.title = title.substring(0,title.length()-3);
                           System.out.println("title:"+topSubjectRecord.title);
                       }

                      matcher2 = _music_rating_num_regular.matcher(pattern_str);
                       if(matcher2.find()){
                           String[] rating_arr = matcher2.group().split(">");
                           String rating = rating_arr[rating_arr.length-1];
                           topSubjectRecord.rating_num = rating.substring(0,rating.length()-5);
                           System.out.println("rating:"+topSubjectRecord.rating_num );
                       }
                       if(topSubjectRecord.image_url!=null && topSubjectRecord.rating_num!=null)
                       regularRecordArrayList.add(topSubjectRecord);
                   }

               } catch (MalformedURLException e) {
                   e.printStackTrace();
               } catch (IOException e) {
                   e.printStackTrace();
               }
              return regularRecordArrayList;
       }


    public static ArrayList<TopSubjectRecord> getHotMovie(){

        ArrayList<TopSubjectRecord> topSubjectRecords = new ArrayList<TopSubjectRecord>();

        StringBuffer stringBuffer = new StringBuffer();
        try{
            URL moview_url = new URL(_movie_url);
            URLConnection httpConnection = moview_url.openConnection();
            InputStreamReader inputStreamReader =
                    new InputStreamReader(httpConnection.getInputStream());
            BufferedReader reader = new BufferedReader(inputStreamReader);
            String temp;

            while ((temp = reader.readLine())!=null){
                stringBuffer.append(temp);
            }

            reader.close();
            inputStreamReader.close();
//            Log.v("DEBUG",stringBuffer.toString());
            Matcher matcher = _movie_regular.matcher(stringBuffer.toString());

            int num = 0;
            while (matcher.find()){
                //fetch 15
                if(num ==15)break;

                TopSubjectRecord topSubjectRecord = new TopSubjectRecord();
                topSubjectRecord.type = Assistant.STATUS_MOVICE;

                String movie_str = matcher.group();
                 Matcher matcher2 = _movie_id_regular.matcher(movie_str);
                if(matcher2.find()){
                    String[] ids = matcher2.group().split("\"");
                    topSubjectRecord.id = ids[ids.length-2].trim();
                }

                matcher2 = _movie_title_regular.matcher(movie_str);
                if(matcher2.find()){
                    String[] titles = matcher2.group().split(">");
                    if(titles.length>3){
                        String title =  titles[titles.length-2];
                        topSubjectRecord.title = title.substring(0,title.length()-3).trim();
                    }
                }

                matcher2 = _movie_img_regular.matcher(movie_str);

                if(matcher2.find()){
                    String[] images = matcher2.group().split("\"");

                    topSubjectRecord.image_url = images[1].trim().replaceFirst("spic","mpic");
                    if(App.NETWORK_STATUS == Assistant.WIFI)
                        topSubjectRecord.image_url = images[1].trim().replaceFirst("spic","lpic");
                }

                matcher2 = _movie_content_regular.matcher(movie_str);
                int i=0;
                while (matcher2.find()){
                    if(i==2){
                    String content = matcher2.group();
                    content = content.substring(17,content.length()-7);
                    topSubjectRecord.content = content.trim();
                    }
                    i++;
                }

//                matcher2 = _movie_rating_average_regular.matcher(movie_str);
//                if(matcher2.find()){
//                    String[] averages = matcher2.group().split(">");
//                    String average = averages[1].substring(0,averages[1].length()-6);
//                    topSubjectRecord.rating_average = average.trim();
//                }

                matcher2 = _movie_rating_num_regular.matcher(movie_str);
                if(matcher2.find()){
                       String[] rating_arr = matcher2.group().split(">");
                           String rating = rating_arr[rating_arr.length-1];
                           topSubjectRecord.rating_num = rating.substring(0,rating.length()-5);
                }
                if(topSubjectRecord.image_url!=null)
                    topSubjectRecords.add(topSubjectRecord);
                num++;
            }

        }catch (MalformedURLException e){
            e.printStackTrace();
        }catch (IOException e){
            e.printStackTrace();
        }

        return topSubjectRecords;
    }


      public static ArrayList<TopSubjectRecord> getNewBook(){
        ArrayList<TopSubjectRecord> topSubjectRecordArrayList =
                        new ArrayList<TopSubjectRecord>();

        StringBuffer stringBuffer = new StringBuffer();
         try {
            URL book_url = new URL(_book_url);
            URLConnection httpConnection = book_url.openConnection();
             InputStreamReader inputStreamReader =
                     new InputStreamReader(httpConnection.getInputStream());
             BufferedReader reader = new BufferedReader(inputStreamReader);
             String  temp;

             while ((temp = reader.readLine())!=null){
                 stringBuffer.append(temp);
             }

             reader.close();
             inputStreamReader.close();

             Matcher matcher = _book_regular.matcher(stringBuffer.toString());

             int i=0;
             while (matcher.find()){
                 System.out.println(matcher.group());
                 TopSubjectRecord topSubjectRecord = new TopSubjectRecord();
                 String group = matcher.group();
                 if(group!=null){

                    //Match title
                     Matcher matcher2 = _book_title_regular.matcher(group);
                    if (matcher2.find()){
                         String h = matcher2.group();
                         h = h.substring(h.indexOf(">")+1,h.indexOf("/")-1).trim();
                         System.out.println("h2:"+h);
                        topSubjectRecord.title = h;
                     }

                     //Match attribut
                     matcher2 = _book_attribute_regular.matcher(group);
                     if(matcher2.find()){
                         String attribute = matcher2.group();
                         attribute = attribute.substring(attribute.indexOf(">")+1,attribute.indexOf("</")-2).trim();
                         System.out.println("attribute:"+attribute+"index:"+matcher2.start());
                         topSubjectRecord.attribute= attribute;
                     }

                     //Match content
                     matcher2 = _book_content_regular.matcher(group);
                     if(matcher2.find()){
                         String content = matcher2.group();
                         content = content.substring(content.indexOf(">")+1,content.indexOf("</p>"));
                         topSubjectRecord.content = content;
                         System.out.println("content:"+content);
                     }

                     //Match id
                     matcher2 = _book_id_regular.matcher(group);
                     if(matcher2.find()){
                         String[] id_arr = matcher2.group().split("\"");
                         topSubjectRecord.id = id_arr[1];
                     }

                     //Match img

                     matcher2 = _book_imag_regular.matcher(group);
                     if(matcher2.find()){
                         String img_url = matcher2.group();
                         String[] img_url_arr = img_url.split("\"");
                         String img = img_url_arr[1];

                         topSubjectRecord.image_url = img.replaceFirst("spic","mpic");
                         if(App.NETWORK_STATUS==Assistant.WIFI){
                             topSubjectRecord.image_url = img.replaceFirst("spic","lpic");
                                topSubjectRecord.image_url = img.replaceFirst("mpic","lpic");
                         }

                     }
                 }

                topSubjectRecordArrayList.add(topSubjectRecord);
                 i++;
                 if(i>=17)
                     break;
             }



        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return topSubjectRecordArrayList;
     }

}
